<template>
  <span
    :id="graphNode.id"
    class="v-model-tree-node"
    :class="{'_drag-hover':isDragOver}"
    draggable
    @dragend="handleDragEnd"
    @dragstart="handleDragStart"
    @dblclick="handleDbClick"
    @click="handleClickNode"
    @dragenter="handleDragEnter"
    @dragleave="handleDragLeave"
    @dragover="handleDragOver"
    @drop="handleDrop"
  >
    <img
      v-if="iconPath"
      :src="iconPath"
      alt="icon"
      class="_tree-node-icon g-pointer "
      @contextmenu="handleContextMenu"
    />
    <a-input
      v-if="graphNode.inEdit"
      ref="nameInput"
      v-model="nameForEdit"
      class="_name-input"
      @blur="handleSaveTitle"
      @pressEnter="handleSaveTitle"
      @click.native.stop
    />
    <span
      v-else
      class="g-m-l-4 _display-title g-pointer"
      :class="{_selected:graphNode.selected,_disabled:graphNode.disabled || graphNode.status === 5}"
      @contextmenu="handleContextMenu"
    >{{displayTitle || '---'}}<span style="color: #914b31">{{getDefaultValue()}}</span>
      <a-tooltip v-if="graphNode.status === 2" placement="right" arrowPointAtCenter>
        <template slot="title">
          <span>已被他人锁定</span>
        </template>
        <a-icon  type="lock" />
      </a-tooltip>
    </span>
  </span>
</template>
<script>
import {
  findNodeByValue, treeForEach
} from 'src/util/common';
import { ContextMenu } from 'components/common/ContextMenu/index';
import treeUtil from './treeUtil';
import { modelApi } from "src/api/model/modelApi";
import { createError } from 'src/constants/ErrorConfig';
import resizeUtil from '@/pages/mxgraph/resizeUtil';
import { actions } from '@/pages/mxgraph/Actions';
import { GraphNodeType } from '@/constants/Enums';
import { GraphNodeUtil } from 'pages/mxgraph/GraphNodeUtil';
import { GraphShapeUtil } from '@/pages/mxgraph/GraphShapeUtil';
import ResizeUtil from '@/pages/mxgraph/resizeUtil';
import { SysMLUtilHelper } from "src/api/sysml-imports";
import { PropertyUtil } from 'src/components/Attribute/comps/PropertyUtil';
import { dumpLog } from '@/constants/ErrorConfig';

export default {
  name: 'comp-tree-node',
  components: {
  },
  props: {
    graphNode: Object,
    toPasteNode: Array,
  },
  data() {
    //// if (this.graphNode.selected === undefined){
    ////   this.$set(this.graphNode, 'selected', false);
    //// }
    return {
      nameForEdit: '',
      isDragOver: false,

    };
  },
  computed: {
    iconPath(){
      try {
        if (this.graphNode.getTypeName() === 'Slot') { //// 对实例值的图标做特殊处理
          const hasInstanceValue = this.children.some(item => item.getTypeName() === 'InstanceValue');
          if (hasInstanceValue) {
            return 'statics/images/sysml/slotInstanceValue.svg';
          }
        }
        const map =  app.activeProject.config.reqMap;
        if ( this.graphNode.getTypeName() === 'Requirement'){
          return map[this.graphNode.id] ? 'statics/images/sysml/Requirement2.svg' : this.graphNode.iconPath;
        }
      } catch (error) {
        
      }    
      return this.graphNode.iconPath;
    },
    displayTitle(){
      return this.graphNode && this.graphNode.displayTitle;
    },
    children(){
      return this.graphNode && this.graphNode.getChildren();
    }

  },
  watch: {
    'graphNode.inEdit'(val){
      if (val){
        this.setInEdit();
      }
    },

  },
  mounted(){
    console.log(this.inEdit, this.displayTitle, '---------');
    this.setInEdit();

  },
  methods: {

    handleClickNode() {
      if (this.graphNode.isVirtual) return; //// 虚节点，前端构造出来的虚节
      dumpLog('selectOnTree', this.graphNode);
      actions.getAction('selectOnTree').run(this.graphNode, { scroll: false });

    },
    handleContextMenu(event) {
      console.log('context menu');
      const model = this.graphNode.model; //// 点击的节点的model
      if (!model) return;
      if ( this.inEdit || this.graphNode.id === '-1') return;
      this.handleClickNode();
      const canCopy = modelApi.canCopy([model]);
      const canPast = this.toPasteNode && modelApi.canPaste(this.toPasteNode.map(i => i.model),  model);
      ContextMenu.popup({
        x: event.clientX,
        y: event.clientY,
        //// TODO
        menuItems: treeUtil.getMenuItems(this.graphNode, { canCopy, canPast })
      }).then(menuItem => {
        console.log(menuItem);
        const action = actions.getAction(menuItem.value);
        if (!action) return;
        //// TODO
        dumpLog('onTreeMenuClick', this.graphNode, menuItem);
        action.onTreeMenuClick(this.graphNode, menuItem);
      }).catch(err => {
        if (err) throw err;
      });

    },

    handleDbClick() {
      const typeConf = app.activeProject.configManager.getTypeNameConfigItem(this.graphNode.getTypeName());
      if (!typeConf) return;
      const canOpenTypes = [GraphNodeType.DIAGRAM, GraphNodeType.MATRIX, GraphNodeType.TABLE, GraphNodeType.RELATION_VIEW];
      if (canOpenTypes.includes(typeConf.type)){
        actions.getAction('openDiagram').run(this.graphNode);

      } else if (this.graphNode.model) {
        actions.getAction('showAttribute').run(this.graphNode);
      }

    },

    //// 获取默认值
    getDefaultValue() {
      if (!this.graphNode.model) return;
      try {
        const defaultValue = PropertyUtil.getNodePropertyValue(this.graphNode, 'DefaultValue');
        if (defaultValue) {
          return '=' + SysMLUtilHelper.getValueSpecificationValue(defaultValue);
        }
      } catch (error) {
        
      }     
      return '';
    },

    //// handleCopy(){
    ////   console.log("handle copy................");
    ////   const modelId = this.selectedKeys[0];
    ////   if (!modelId) return;
    ////   const node = findNodeByValue(this.treeData, modelId);
    ////   if (!node) return;
    ////   this.copy(node);

    //// },
    //// handlePaste(){
    ////   const modelId = this.selectedKeys[0];
    ////   if (!modelId) return;
    ////   const node = findNodeByValue(this.treeData, modelId);
    ////   if (!node) return;
    ////   this.paste(node);

    //// },
    //// copy(node){
    ////   const canCopy = modelApi.canCopy([node.model]);
    ////   if (!canCopy) return;
    ////   this.toPasteNode = [node];

    //// },
    //// paste(node){
    ////   console.log('ppppp');
    ////   if (this.toPasteNode.length === 0) return;
    ////   const canPaste = modelApi.canPaste(this.toPasteNode.map(i => i.model), node.model);
    ////   if (!canPaste){
    ////     throw createError(errcode.PASTE_NOT_ALLOW);
    ////   }
    ////   console.log("coppppppy");
    ////   modelApi.copyModel(this.toPasteNode.map(i => i.model), node.model);
    ////   this.$bus.emit('model-add', {});
    ////   this.$bus.emit('fresh-graph');
    //// },
    handleEsc(){
      this.toPasteNode = [];

    },
    handleDragStart() {

      treeUtil.setDragData(this.graphNode);
    },
    handleDragEnd(event) {
      treeUtil.setDragData(undefined);
      this.$bus.emit('remove-graph-highlight');
    },

    setInEdit(){
      if (!this.graphNode.inEdit) return;
      this.nameForEdit = this.graphNode.title;
      this.$nextTick(() => {
        const input = this.$refs.nameInput;
        console.log(input);

        if (input){
          input.focus();
          input.select();
        }

      });

    },
    handleSaveTitle() {
      if (this.graphNode.inEdit === false) return; //// 防止blur 与enter重复触发
      if (this.graphNode.name === this.nameForEdit) {
        this.graphNode.inEdit = false;
        return;
      }
      this.graphNode.updateName(this.nameForEdit);
      this.graphNode.inEdit = false;
      ResizeUtil.updateNodeShapes( this.graphNode, true);
 
      app.$bus.emit('model-update', { id: this.graphNode.id });
      app.$bus.emit('project-modified');

    },

    handleDragEnter(){
      this.isDragOver = true;
      //// data.dragOver = true;
    },
    handleDragLeave(){
      this.isDragOver = false;
      //// data.dragOver = false;
    },
    handleDragOver(event){
      //// 防止图片拖拽时页面跳走
      window.event.stopPropagation();
      window.event.preventDefault();
      //// let element = app.selectedElement;
      //// let flag = graphUtil.isValidDropTargetElement(element, this.graphNode.model);
      //// //// flag为flase时，显示不可drop的图标
      //// if (!flag) {
      ////   event.preventDefault();
      ////   event.dataTransfer.dropEffect = 'none';
      //// }
    },
    handleDrop(){
      this.isDragOver = false;
      let sourceNode = treeUtil.getDragData();
      let targetNode = this.graphNode;
      console.log('drop');
      //// TODO
      let valid = GraphNodeUtil.isValidChildNode(sourceNode, targetNode);
      if (valid) {
        //// TODO
        sourceNode.updateContainer(targetNode);

        const configItem = app.configManager.getTypeNameConfigItem(sourceNode.getTypeName());
        //// if (configItem){
        ////   if (configItem.type === GraphNodeType.DIAGRAM){
        ////     this.$bus.emit('fresh-graph');
        ////   }
        //// }
        app.$bus.emit('fresh-graph');
        app.$bus.emit('model-update', { });
        app.$bus.emit('project-modified');
      }
    },
    log(str){
      console.log(str);
    },

    isFirstNode(graphNode) {
      if (app.sysmlModel){
        const rootIdMap = app.sysmlModel.rootIdMap || {};
        return rootIdMap[graphNode.id];
      }
    }
  }
};
</script>
<style lang="scss">
.v-model-tree-node {
  height:24px;
  padding-top:2px;
  padding-bottom:2px;
  ._tree-node-icon {
    position: relative;
    top: -2px;
    left: 2px;
    width:16px;
    height:16px

  }
  ._name-input {
    height: 19px;
    font-size: 12px;
    line-height: 19px;
    width: 128px;
    margin-left: 8px;
    border-radius: 0px;
  }
  ._display-title {
    color: #202020;
    &._selected {
      background-color: #3483b8;
      color: #fff ;
    }
    &._disabled {
      color: lightgray;
      &._selected {
         color: #fff ;
      }

    }

  }
  &._drag-hover {
    background: dodgerblue;
    * {
        pointer-events: none;
    }
  }
}
</style>
